package cn.edu.bjfu.practice.practice.teacher.service.impl;

import cn.edu.bjfu.practice.practice.teacher.dao.DocumentDao;
import cn.edu.bjfu.practice.practice.teacher.dao.ResourceDao;
import cn.edu.bjfu.practice.practice.teacher.pojo.domain.Document;
import cn.edu.bjfu.practice.practice.teacher.pojo.domain.Resource;
import cn.edu.bjfu.practice.practice.teacher.pojo.query.AddCaseForm;
import cn.edu.bjfu.practice.practice.teacher.pojo.query.AddOneResForm;
import cn.edu.bjfu.practice.practice.teacher.pojo.query.ModifyCaseForm;
import cn.edu.bjfu.practice.practice.teacher.pojo.vo.CaseView;
import cn.edu.bjfu.practice.practice.teacher.service.CaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

@Service
public class CaseServiceImpl implements CaseService {

    @Autowired
    DocumentDao documentDao;

    @Autowired
    ResourceDao resourceDao;

    @Value("${case.basePath}")
    String casePath;

    @Override
    public List<String> addCase(AddCaseForm form) {
        Document userDocument = new Document();
        userDocument.setName(form.getName());
        userDocument.setCourse_id(form.getCourse_id());
        documentDao.insert(userDocument);

        List<String> unsavedFiles = new LinkedList<>();
        form.getResources().forEach(addResourceForm -> {
            String dirPath = casePath + "/" + userDocument.getId();
            String fileName = nameByTime(addResourceForm.getFile());
            File file = new File(new File(dirPath).getAbsolutePath() + "/" + fileName);
            // 检测是否存在目录
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();// 新建文件夹
            }
            try {
                addResourceForm.getFile().transferTo(file);
            } catch (IOException e) {
                unsavedFiles.add("上传失败文件：" + addResourceForm.getResourceName() + "，错误原因：" + e.getLocalizedMessage());
            }
            Resource resource = new Resource();
            resource.setName(addResourceForm.getResourceName());
            resource.setType(addResourceForm.getType());
            resource.setCase_id(userDocument.getId());
            resource.setPath(userDocument.getId() + "/" + fileName);
            resourceDao.insert(resource);
        });
        return unsavedFiles;
    }

    @Override
    public List<Document> selectCase(Integer id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("course_id", id);
        map.put("deleted", false);
        return documentDao.selectByMap(map);
    }

    @Override
    public CaseView getCase(Integer id) {
        Document document = documentDao.selectById(id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("case_id", document.getId());
        List<Resource> resources = resourceDao.selectByMap(map);
        CaseView caseView = new CaseView();
        caseView.setId(document.getId());
        caseView.setName(document.getName());
        caseView.setResources(resources);
        return caseView;
    }

    @Override
    public void modifyCase(ModifyCaseForm form) {
        Document document = new Document();
        document.setId(form.getId());
        document.setName(form.getName());
        documentDao.updateById(document);
    }

    @Override
    public void deleteCase(Integer id) {
        Document document = new Document();
        document.setId(id);
        document.setDeleted(true);
        documentDao.updateById(document);
    }

    @Override
    public int addResource(AddOneResForm form) {

        String dirPath = casePath + "/" + form.getCase_id();
        String fileName = nameByTime(form.getFile());
        File file = new File(new File(dirPath).getAbsolutePath() + "/" + fileName);
        // 检测是否存在目录
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();// 新建文件夹
        }
        try {
            form.getFile().transferTo(file);
        } catch (IOException e) {
            return 0;
        }
        Resource resource = new Resource();
        resource.setName(form.getResourceName());
        resource.setType(form.getType());
        resource.setCase_id(form.getCase_id());
        resource.setPath(form.getCase_id() + "/" + fileName);
        return 1;
    }

    @Override
    public void deleteResource(Integer id) {
        Resource resource = new Resource();
        resource.setId(id);
        resource.setDeleted(true);
        resourceDao.updateById(resource);
    }

    //根据案例及时间生成文件名称(时间+三位随机数+文件后缀名)
    private String nameByTime(MultipartFile file) {
        //获取当前时间的时间戳
        long millis = System.currentTimeMillis();

        Random random = new Random();
        int end3 = random.nextInt(999);
        //如果不足三位前面补0
        String str = millis + String.format("%03d", end3);

        String originalFileName = file.getOriginalFilename();
        assert originalFileName != null;

        return String.valueOf(millis) + str + originalFileName.substring(originalFileName.lastIndexOf("."));
    }
}
